
#导入pymysql库
import pymysql

#构造stuClass类
class stuClass:
	
	#定义析构函数
	def __init__(self):

		#链接数据库
		self.db = pymysql.connect(host ="localhost", user="root", password="",db="mydemo", charset="utf8")
		#定义光标
		self.cursor = self.db.cursor()

		print( "构造函数")

	#定义查询函数
	def findAll(self):
		
		#全选MYSQL语句
		sql = "select * from stu"
		#异常处理过程
		try:

			#执行SQL语句
			self.cursor.execute(sql)
			#输出多少条语句被执行
			print("结果条数: ", self.cursor.rowcount)
			#循环输出数据库内容
			while True:
				data = self.cursor.fetchone()
				if data == None:
					break;
				print(data)
		# alist = cursor.fetchall()
		# for vo in alist:
		# print(vo)
		
		#抛出异常
		except Exception as err:
			print("SQL except ERROR",err)
		
	#定义删除函数
	def deleteData(self,idNo):
		
		sql = "delete from stu where id =%d" %((int)(idNo))

		try:

			self.cursor.execute(sql)
			#事物提交
			self.db.commit()

			print("成功删除条数: ", self.cursor.rowcount)
		except Exception as err:
			#事物回滚
			self.db.rollback
			print("SQL except ERROR",err)

			#cursor.excute("delate from stu")

	#定义插入函数
	def insertData(self,data):
		
		#sql ="insert into stu(name,age, sex,classid) values("%s","%d","%s","%s")"%(data)

		# sql = "insert into stu(name,age,sex,classid) values('%s','%d','%s','%s')"%(data["name"],(tinyint)(data["age"]),data["sex"],data["classid"])
		#sql = "insert into stu(name,age,sex,classid) values('%s','%d','%s','%s')"%(data)
		sql = "insert into stu(name,age,sex,classid) values('%s','%d','%s','%s');"%(data["name"],(int)(data["age"]),data["sex"],data["classid"])

		try:

			self.cursor.execute(sql)
			#事物提交
			self.db.commit() 

			print("成功添加条数: ", self.cursor.rowcount)

		except Exception as err:

			#事物回滚
			self.db.rollback()
			print("SQL except ERROR",err)

	#定义解析函数
	def __del__(self):

		#关闭数据库
		self.db.close()

		print("析构函数")

#s = stuClass()

#data = ("uu100",20,'w','python04')
#s.findAll()
#s.insertData(data)
#s.deletData(15)



